﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QueXian.Models;
namespace QueXian.Controllers
{
    public class DefaultController : Controller
    {
        Model1 mo = new Model1();
        // GET: Default
        public ActionResult Index(int deviceid=0,string content="",int defectState = 0)
        {
            var list = mo.Device.ToList();
            list.Insert(0, new Device() { DeviceName = "全部", DeviceID = 0 });
            ViewBag.DeviceID = new SelectList(list, "DeviceID", "DeviceName");
            var one = mo.Defect.Where(p => p.Content.Contains(content) && (deviceid == 0 || p.DeviceID == deviceid) && (defectState == 0 || p.DefectState == defectState)).ToList();
            return View(one);
        }
        [HttpPost]
        public ActionResult Delete(int? id) 
        {
            if (id == null)
            {
                return Json("Index");
            }
            var task = mo.Defect.Where(p => p.DefectID == id).FirstOrDefault();
            if (task == null)
            {
                return Json("Index");
            }
            mo.Defect.Remove(task);
            var res = mo.SaveChanges();
            if (res > 0)
            {
                return Json(res);
            }
            return Json(false);
        }
        public ActionResult Create()
        {
            ViewBag.DeviceID = new SelectList(mo.Device, "DeviceID", "DeviceName");
            return View();
        }
        [HttpPost]
        public ActionResult Create(Defect task)
        {
            if (ModelState.IsValid)
            {
                task.AddTime = DateTime.Now;
                task.DealTime = null;
                task.DefectState = 1;
                mo.Defect.Add(task);
                var res = mo.SaveChanges();
                if (res > 0)
                {
                    return RedirectToAction("Index");
                }
            }
            ViewBag.DeviceID = new SelectList(mo.Device, "DeviceID", "DeviceName");
            return View(task);
        }
        [HttpPost]
        public ActionResult Edit(int id)
        {
            if (ModelState.IsValid)
            {
                var list = mo.Defect.FirstOrDefault(p => p.DefectID == id);
                if (list != null)
                {
                    list.DealTime = DateTime.Now;
                    list.DefectState = 2;
                    var res = mo.SaveChanges() > 0;
                    return Json(res);

                }
            }
            return Json(false);
        }
    }
}